<script lang="ts" setup>
import type { VbenFormSchema } from '@vben/common-ui'

import { computed, ref } from 'vue'

import { AuthenticationCodeLogin, z } from '@vben/common-ui'
import { $t } from '@vben/locales'

import { message } from 'ant-design-vue'

import { fetchSendSms } from '#/api'
import { useAuthStore } from '#/store'

defineOptions({ name: 'CodeLogin' })
const authStore = useAuthStore()
const loading = ref(false)
const formRef = ref<InstanceType<typeof AuthenticationCodeLogin>>()
const formSchema = computed((): VbenFormSchema[] => {
    return [
        {
            component: 'VbenInput',
            componentProps: {
                placeholder: $t('authentication.mobile')
            },
            fieldName: 'mobile',
            label: $t('authentication.mobile'),
            rules: z
                .string()
                .min(1, { message: $t('authentication.mobileTip') })
                .refine((v) => /^\d{11}$/.test(v), {
                    message: $t('authentication.mobileErrortip')
                })
        },
        {
            component: 'VbenPinInput',
            componentProps: {
                handleSendCode,
                createText: (countdown: number) => {
                    const text =
                        countdown > 0
                            ? $t('authentication.sendText', [countdown])
                            : $t('authentication.sendCode')
                    return text
                },
                placeholder: $t('authentication.code')
            },
            fieldName: 'code',
            label: $t('authentication.code'),
            rules: z.string().min(1, { message: $t('authentication.codeTip') })
        }
    ]
})

async function handleSendCode() {
    const formApi = formRef.value?.getFormApi()

    if (formApi) {
        // 登录失败重置验证码
        const values = await formApi.getValues()
        const { mobile } = values
        if (!mobile) {
            message.info($t('authentication.mobileTip'))
            // eslint-disable-next-line no-throw-literal
            throw 'error'
        }

        if (!/^\d{11}$/.test(mobile)) {
            message.info($t('authentication.mobileErrortip'))
            // eslint-disable-next-line no-throw-literal
            throw 'error'
        }

        await fetchSendSms({ mobile })
    }
}
/**
 * 异步处理登录操作
 * Asynchronously handle the login process
 */
async function handleLogin() {
    const formApi = formRef.value?.getFormApi()

    if (formApi) {
        const values = await formApi.getValues()
        const { mobile, code } = values

        console.log('login', values)
        await authStore.authLogin({ mobile, code })
    }
}
</script>

<template>
    <AuthenticationCodeLogin
        ref="formRef"
        :form-schema="formSchema"
        :loading="loading"
        @submit="handleLogin"
    />
</template>
